package com.wing.web.excel;

import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtils {

    public static List<List<String>> readExcel(MultipartFile file) throws IOException {
        List<List<String>> result = new ArrayList<>();

        // 获取文件输入流
        try (InputStream inputStream = file.getInputStream()) {
            // 根据文件后缀创建不同的Workbook
            Workbook workbook = WorkbookFactory.create(inputStream);

            // 获取第一个Sheet
            Sheet sheet = workbook.getSheetAt(0);

            // 遍历所有行
            for (Row row : sheet) {
                List<String> rowData = new ArrayList<>();

                // 遍历所有单元格
                for (Cell cell : row) {
                    // 根据单元格类型获取值
                    String cellValue = getCellValue(cell);
                    rowData.add(cellValue);
                }

                result.add(rowData);
            }
        }

        return result;
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 数字类型，避免科学计数法
                    return String.valueOf((long) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return "";
        }
    }
}

